var div;
var arrayMovies;
var moviesDisplay;
var ids = new Array();
var idFilter = 0;
var orderFilter = "asc";
var urlServer = "getAllMovie.php";
var token = "ccf4ea1073d17b7640fc146a324d8b2a";
(function(a){
	$.fn.extend({
		loadMiniaturasMovie : function(options) {
			var defaults = {
				fileMovies : urlServer
			}
			var options = $.extend(defaults, options);
			moviesDisplay = new Array();
			div = this;
			showLoadIcon(true);
			loadJsonFile(options.fileMovies);
		}
	});
})(jQuery);

function showLoadIcon(sw){
	if(sw==true){
		$("#loadIcon").css("display","block");
		$("#loadIcon").stop(true,false).animate({
			"opacity":1
		},500);	
	}else{
		$("#loadIcon").stop(true,false).animate({
				"opacity":0
		},500,function(){
			$("#loadIcon").css("display","none");
		});
	}
}

function procesarJson(movies){
	arrayMovies = new Array();
	movies.forEach(function(value){
		arrayMovies[value.idMovie] = value;
	});
	var html = '<div id="loadIcon"></div>';
	html += loadFilter();
	html += '<div id="miniaturasAP">';
	html += crearMiniaturas(movies);
	html += '<div style="clear:both"></div>';
	html += '</div>';
	html += '<div id="loadPag"></div>';
	html += loadDetailMovie();
	div.html(html);
	var i = 0;
	actionClickFilter();
	actionClick(movies);
	animarMiniaturas(movies,i);
}

function crearMiniaturas(movies){
	var html = "";
	var i=0;
	movies.forEach(function(value){
		moviesDisplay[i] = value;
		html += loadMiniatura(value);
		i++;
	});
	return html;
}

function loadDetailMovie(){
	var esqueleto =
		'<div id="detailMovie">'
			+'<div id="returnToMiniaturas"> &#60; Volver</div>'
			+'<div id="coverMovie"><img id="imageCover" src="" style="width:100%" /></div>'
			+'<div id="infoMovie">'
				+'<div id="titleMovie"></div><div id="yearMovie"></div><div style="clear:both"></div>'
				+'<div id="originalTitleMovie"></div>'
				+'<div id="propertiesMovie"></div>'
				+'<div id="dataMovie"></div>'
				+'<div id="sinopsisMovie"></div>'
			+'</div>'
			+'<div style="clear:both"></div>'
			+'<div id="titleTrailer"></div>'
			+'<div id="trailerMovie"><iframe id="frameYoutube" class="youtube-player" type="text/html" style="width:100%; height:600px" src="#" frameborder="0"></iframe></div>'
		+'</div>';
	return esqueleto;
}

function actionClick(movies){
	movies.forEach(function(value){
		$("#mov-"+value.idMovie).click(function(){
			showLoadIcon(true);
			$("#filter").stop(true,false).animate({
				"opacity":"0"
			},500,function(){
				$("#filter").css("display","none");
			});
			$("#miniaturasAP").stop(true,false).animate({
				"opacity":"0"
			},500,function(){
				$("#miniaturasAP").css("display","none");
				showDetail(value.idMovie);
				animarDetail();
			});
			$("html").scrollTop(0);
		});
	});
	$('#returnToMiniaturas').click(function(){
		ocultarDetail();
	});
}

function mostrarMiniaturas(){
	$(".miniatura").css("opacity","0");
	$("#miniaturasAP").css("opacity","1");
	$("#miniaturasAP").css("display","block");
	var i=0;
	showLoadIcon(false);
	animarMiniaturas(arrayMovies,i);
}

function ocultarDetail(){
	showLoadIcon(true);
	$('#detailMovie').animate({
		"opacity":"0"
	},500,function(){
		$("#detailMovie").css("display","none");
		$("#filter").css("display","table");
		$("#filter").stop(true,false).animate({
			"opacity":"1"
		},500);
		showLoadIcon(false);
		mostrarMiniaturas();
	});
}

function showDetail(id){
	var buffer = arrayMovies[id];
	var date = buffer.releaseDate.split("-");
	$('#titleMovie').html(atob(buffer.title));
	$('#originalTitleMovie').html(buffer.originalTitle);
	$('#yearMovie').html(date[0]);
	$("#imageCover").attr("src","images/movies/"+buffer.image);
	$('#propertiesMovie').html(showProperties(buffer));
	$('#dataMovie').html(showDataMovie(buffer));
	$('#sinopsisMovie').html(buffer.sinopsis);
	$("#frameYoutube").attr("src", "http://www.youtube.com/embed/"+buffer.youTube);
}

function showDataMovie(movie){
	strGenre = "";
	if(movie.genre.length>0 && movie.genre !="0x0"){
		movie.genre.forEach(function(genre){
			strGenre = strGenre+atob(genre.nameGenre)+", ";
		});
		strGenre = strGenre.substring(0,strGenre.length-2);
	}
	var buffer =
		'<table width="100%">'
			+'<tr>'
				+'<td width="20%">Genero</td>'
				+'<td width="80%">'+strGenre+'</td>'
			+'</tr><tr>'
				+'<td>Clasificación</td>'
				+'<td>'+movie.mpaa+'</td>'
			+'</tr><tr>'
				+'<td>Duración</td>'
				+'<td>'+movie.duration+' minutos</td>'
			+'</tr><tr>'
				+'<td>Nota IMDB</td>'
				+'<td>'+movie.imdbRating+'</td>'
			+'</tr>'
		+'</table>';
	return buffer;
}

function showProperties(movie){
	var buffer = "";
	if(movie.video.length>0 && movie.video !="0x0"){
		movie.video.forEach(function(video){
			buffer += '<div class="det">'+video.nameVideo+'</div>';
		});
	}
	if(movie.audio.length>0 && movie.audio !="0x0"){
		movie.audio.forEach(function(audio){
			buffer += '<div class="det">'+atob(audio.nameAudio)+'</div>';
		});
	}
	buffer += '<div style="clear:both"></div>';
	return buffer;
}

function animarMiniaturas(movies, i){
	var value = movies[i];
	i++;
	$("#mov-"+value.idMovie).css("opacity","0");
	$("#mov-"+value.idMovie).stop(true,false).animate({
		"opacity":"1",
	},200, function(){
		if(i<movies.length){
			animarMiniaturas(movies, i);
		}
	});
}

function animarDetail(){
	$('#detailMovie').css("display","block");
	$('#detailMovie').css("opacity","0");
	$('#trailerMovie').css("opacity","0");
	$('#coverMovie').css({"opacity":"0","margin-left":"200px"});
	$('#infoMovie').css({"opacity":"0","margin-top":"50px"});
	setTimeout(function(){
		$("#detailMovie").stop(true,false).animate({
			"opacity":1
		},300,function(){
			showLoadIcon(false);
			$("#coverMovie").stop(true,false).animate({
				"opacity":1,
				"margin-left":0	
			},500,function(){
				$("#infoMovie").stop(true,false).animate({
					"opacity":1,
					"margin-top":0
				},500);	
				$("#trailerMovie").stop(true,false).animate({
					"opacity":1	
				},500);	
			});
		});
	},1000);
}
function loadMiniatura(movie){
	var defaults = {
		idMovie : 0,
		title : "",
		originalTitle : "",
		image : "default.jpg",
		releaseDate : "",
		genre: "",
		idMpaa: "",
		nameMpaa : "",
		duration: "",
		video1: "",
		video2: "",
		audio1: "",
		audio2: "",
		date: "",
		imdbRating: "",
		imdbCode: "",
		sinopsis: "",
		youtubeCode: ""
	}
	var parametros = {
		urlCover : "images/movies/",
		urlMovie : "movie.html",
		urlSerie : "serie.html"
	}
	var movie = $.extend(defaults, movie);
	var propiedades = "";
	if(movie.video.length>0 && movie.video !="0x0"){
		movie.video.forEach(function(video){
			propiedades += '<div class="det propiedad">'+video.nameVideo+'</div>';
		});
	}
	if(movie.audio.length>0 && movie.audio !="0x0"){
		movie.audio.forEach(function(audio){
			propiedades += '<div class="det propiedad">'+atob(audio.nameAudio)+'</div>';
		});
	}
	var esqueleto = 
		'<div class="miniatura" id="mov-'+movie.idMovie+'">'
			+'<div class="coverMin"><img src="'+parametros.urlCover+movie.image+'" style="width:100%" /></div>'
			+'<span class="title">'+atob(movie.title)+'</span><br><span class="year">'+movie.year+'</span>'
			+'<br>'
			+propiedades
		+'</div>';
	return esqueleto;
}

function loadJsonFile(file){
	var buffer =0;
	$.post(file, {token : token})
	.done(function(data){
		try{
			data = jQuery.parseJSON(data);
		}catch(e){
			console.log(data);
			alert("Error al obtener información necesaria");
		}
		if(data.code=="0x0"){
			procesarJson(data.data);
		}else{
			alert("Error al obtener los datos desde el servidor. Reintente.");
		}
	});
}

function loadFilter(){
	var html = 
	'<div id="filter">'
		+'<div class="buttonFilter" id="filter-1">Todos</div>'
		+'<div class="buttonFilter" id="filter-2">Fecha estreno</div>'
		+'<div class="buttonFilter" id="filter-3">1080p</div>'
		+'<div class="buttonFilter" id="filter-4">3D</div>'
		+'<div class="buttonFilter" id="filter-5">Latino</div>'
		+'<div class="buttonFilter" id="filter-6">Ingles</div>'
		+'<div style="clear:both"></div>'
	+'</div>';
	return html;
}

function actionClickFilter(){
	$(".buttonFilter").click(function(){
		var id = this.id.split("-");
		id = id[1];
		filtrarMovie(id);
	});
}

function filtrarMovie(id){
	var movies = new Array();
	arrayMovies.forEach(function(value){
		movies[movies.length] = value;
	});
	if(id==2){
		movies.sort(compareFecha);
	}
	if(id==3){
		movies = filtrar1080p(movies);
	}
	if(id==4){
		movies = filtrar3D(movies);
	}
	if(id==5){
		movies = filtrarLatino(movies);
	}
	if(id==6){
		movies = filtrarIngles(movies);
	}
	if(id==idFilter && orderFilter=="asc"){
		movies.reverse();
		orderFilter="desc";
	}else{
		idFilter=id;
		orderFilter="asc";
	}
	moviesDisplay = movies;
	var html = crearMiniaturas(movies);
	$("#miniaturasAP").html(html);
	if(movies.length>1){
		var i=0;
		animarMiniaturas(movies,i);
		actionClick(movies);
	}
}

function filtrar1080p(movies){
	var buffer = new Array();
	movies.forEach(function(value){
		if(value.video1 == "1080p" || value.video2 == "1080p") {
			buffer[buffer.length] = value;
		}
	});
	return buffer
}

function filtrar3D(movies){
	var buffer = new Array();
	movies.forEach(function(value){
		if(value.video1 == "3D" || value.video2 == "3D") {
			buffer[buffer.length] = value;
		}
	});
	return buffer
}

function filtrarLatino(movies){
	var buffer = new Array();
	movies.forEach(function(value){
		if(value.audio1 == "Español Latino" || value.audio2 == "Español Latino") {
			buffer[buffer.length] = value;
		}
	});
	return buffer
}

function filtrarIngles(movies){
	var buffer = new Array();
	movies.forEach(function(value){
		if(value.audio1 == "Ingles" || value.audio2 == "Ingles") {
			buffer[buffer.length] = value;
		}
	});
	return buffer
}

function compareFecha(a,b) {
	a = new Date(a.date);
	b = new Date(b.date);
  if (a < b)
     return -1;
  if (a > b)
    return 1;
  return 0;
}